<template>
    <div class="main">
        <!-- <h1>私教课程</h1> -->
        <div class="search">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="课程名称">
                    <el-input v-model="formInline.name" placeholder="请输入课程名称" clearable />
                </el-form-item>
                <el-form-item label="课程类型">
                    <el-select v-model="formInline.type" clearable placeholder="课程分类">
                        <el-option v-for="item in keType" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="适用人群">
                    <el-select v-model="formInline.applyTo" clearable placeholder="课程适用人群">
                        <el-option v-for="item in apply" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="最低价格">
                    <el-input-number v-model="formInline.minPrice" placeholder="最低价格" :precision="2"  :step="100" :min="0" @change="minChange" />
                </el-form-item>
                <div>
                    <el-form-item label="最高价格" style="margin: 0 32px 0 0;">
                        <el-input-number v-model="formInline.maxPrice" :min="0" placeholder="最高价格" :precision="2" :step="100" @change="maxChange" />
                    </el-form-item>
                    <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                    <el-button :icon="Refresh" @click="onSubmit">重置</el-button>
                </div>
            </el-form>
        </div>
        <div class="button">
            <div>
                <el-button type="primary" plain :icon="Plus" @click="show">新增</el-button>
                <el-button type="success" :icon="Edit" plain :disabled="multipleSelection.length !== 1" @click="editShow()">修改</el-button>
                <el-button type="danger" :icon="Delete" plain :disabled="multipleSelection.length == 0" @click="deleteClue()">删除</el-button>
                <el-button type="warning" :icon="Download" plain  @click="exportXlsx">导出</el-button>
            </div>
            <div>
                <el-tooltip class="box-item" effect="dark" content="隐藏搜索" placement="top" >
                    <el-button :icon="Search" size="small" circle @click="noSearch" />
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="刷新" placement="top">
                    <el-button :icon="Refresh" size="small" circle @click="reGet" />
                </el-tooltip>
            </div>
        </div>
        <div class="table">
            <el-table :data="tableData" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" align="center" width="55" />
                <el-table-column property="courseId" label="课程编号" align="center" width="80">
                </el-table-column>
                <el-table-column property="type" label="课程类型" align="center" width="120">
                    <template #default="scope">
                        <el-tag v-if="scope.row.type === 2" type="success">游泳类</el-tag>
                        <el-tag v-if="scope.row.type === 1" >舞蹈类</el-tag>
                        <el-tag v-if="scope.row.type === 3" type="info">拳击类</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="name" label="课程名称" show-overflow-tooltip align="center" width="120"/>
                <el-table-column property="price" label="课程价格" align="center" width="120" />
                <el-table-column property="applyTo" label="课程适用人群" align="center" width="150">
                    <template #default="scope">
                        <el-tag v-if="scope.row.applyTo === 1" >中小学生</el-tag>
                        <el-tag v-if="scope.row.applyTo === 2" type="success">上班族</el-tag>
                        <el-tag v-if="scope.row.applyTo === 3" type="info">小白用户</el-tag>
                        <el-tag v-if="scope.row.applyTo === 4" type="warning">健身达人</el-tag>
                    </template>              
                </el-table-column>
                <el-table-column property="info" label="课程简介" show-overflow-tooltip align="center" width="180" />
                <el-table-column property="createTime" label="创建时间" align="center" width="180">
                    <template #default="scope">
                        {{ scope.row.createTime.split('T')[0]+ '     ' + scope.row.createTime.split('T')[1] }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button :icon="Edit" link type="primary" size="small" @click="edit(scope.row)">
                            修改
                        </el-button>
                        <el-button  :icon="Delete" link type="primary" size="small" @click="del(scope.row.courseId)">
                        删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 模态框 -->
        <el-dialog v-model="dialogVisible" :title="title" width="40%">
            <div>
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="课程分类" prop="type" placeholder="课程分类">
                                <el-select v-model="ruleForm.type" clearable placeholder="课程分类">
                                    <el-option v-for="item in keType" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="课程名称" prop="name" placeholder="请输入课程名称">
                                <el-input v-model="ruleForm.name" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="适用人群" prop="applyTo">
                                <el-select v-model="ruleForm.applyTo" clearable placeholder="课程适用人群">
                                    <el-option v-for="item in apply" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="课程价格" prop="price">
                                <el-input-number v-model="ruleForm.price" placeholder="课程价格" :precision="2"  :step="100" @change="minChange" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="课程简介" prop="info">
                        <el-input v-model="ruleForm.info" placeholder="请输入内容" type="textarea"/>
                    </el-form-item>
                    <el-form-item style="display: flex;">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">
                            取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 分页器 -->
        <div class="fenYe">
            <el-pagination layout="total, sizes, prev, pager, next, jumper" :pageParams="pageParams" :total="total" :page-sizes="[10, 20, 30, 50]" background @size-change="pageChange" @currentChange="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import { Refresh, Search, Plus, Delete, Edit, Download, } from '@element-plus/icons-vue';
import { list, add, Xiu, gai, delEte, chu } from "@/api/course"; 
import { FormInstance, FormRules,ElMessage, ElMessageBox } from 'element-plus';

// 搜索框的
const maxChange = (value: number | undefined) => {
    console.log(value);
};
const minChange = (value: number | undefined) => {
    console.log(value);
};
interface search {
    pageNum:number,
    pageSize: number,
    applyTo:null,
    name: string,
    type: null,
    minPrice: null,
    maxPrice: null
}
// 搜索时用的数据
const formInline =  reactive < search >({
    pageNum: 1,
    pageSize: 10,
    applyTo: null,
    name: '',
    type: null,
    minPrice: null,
    maxPrice: null
});
// 点击搜索
const search = () => {
    console.log(formInline);
    list(formInline).then(res => {
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
    });
};
// 点击重置
const onSubmit = () => {
    Object.keys(formInline).forEach(key => {
        formInline[key] = null;
    });
    console.log(formInline);
    getList();
};


// 模态框
// 控制模态框的开关
const dialogVisible = ref(false); 
// 标题
let title = ref('');
// 点击新增
function show() {
    dialogVisible.value = true;
    title.value = "新增";
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields();
    });
}
// 数据接口
interface RuleForm {
    applyTo:number,
    info: string,
    name: string,
    price: number,
    type: number,
}
const ruleFormRef = ref < FormInstance > ();
const ruleForm = reactive < RuleForm > ({
    applyTo:null,
    info: null,
    name: null,
    price: null,
    type: null,
});
// 适用人群
const apply = [
    {
        label: "中小学生",
        value: 1
    },
    {
        label: "上班族",
        value: 2
    }, 
    {
        label: "小白用户",
        value: 3
    },
    {
        label: "健身达人",
        value: 4
    },
];
// 课程分类
const keType = [
    {
        label: "游泳类",
        value: 2
    },
    {
        label: "舞蹈类",
        value: 1
    }, 
    {
        label: "拳击类",
        value: 3
    }
];
const rules = reactive < FormRules < RuleForm >> ({
    name: [
        { required: true, message: '课程名称不能为空', trigger: 'blur' }
    ],
    applyTo: [
        { required: true, message: '适用人群不能为空', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '课程分类不能为空', trigger: 'blur' }
    ],
    info: [
        { required: true, message: '课程简介不能为空', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入一个价格', trigger: 'blur' }
    ],
});

// 点击确定
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === "新增") {
                // 新增接口
                add(ruleForm).then(res => {
                    console.log(res);
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    });
                    dialogVisible.value = false;
                    getList();
                })
                    .catch(err => {
                        console.log(err);
                    });
            }else{
                // 修改
                gai({
                    courseId: id.value,
                    ...ruleForm
                }).then(res => {
                    console.log(res);
                    ElMessage.success("修改成功");
                    dialogVisible.value = false;
                    getList();
                });
            }
        } else {
            console.log('error submit!', fields);
        }
    });
};

// 点击取消并且重置弹框
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    dialogVisible.value = false;
};

// 表格数据
interface User {
    // 课程编号
    courseId: number
    // 课程类型
    type:number
    // 课程名称
    name: string
    // 课程价格
    price: number
    // 课程适用人群
    applyTo: number
    // 课程简介
    info: string
    // 创建时间
    createTime: ""
}
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
});
const tableData: User[] = ref([]);
// 列表展示
function getList() {
    list(pageParams).then(res => {
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
        console.log(tableData);
    });
};
onMounted(() => {
    getList();
});

let id = ref(0);
// 编辑
function edit(row:any) {
    console.log(row);
    dialogVisible.value = true;
    title.value = "修改课程";
    // 获取详情
    Xiu(row.courseId).then(res => {
        console.log(res);
        let jie = res.data;
        id.value = jie.courseId;
        ruleForm.applyTo = jie.applyTo;
        ruleForm.name = jie.name;
        ruleForm.info = jie.info;
        ruleForm.type = jie.type;
        ruleForm.price = jie.price;
    })
        .catch(err => {
            console.log(err);
        });
}

// 分页器部分
let total = ref(0);

const pageChange = (val: number) => {
    pageParams.pageSize = val;
    pageParams.pageNum = 1;
    getList();
};

const handleCurrentChange = (val: number) => {
    pageParams.pageNum = val;
    console.log(val);
    getList();
};

// 两个按钮
// 隐藏搜索
function noSearch(){
    let search = document.querySelector(".search");
    if (!search) {
        console.warn("未找到 .search 元素！");
        return;
    }else{
        if (search.style.display === "none") {
            search.style.display = "block"; // 显示
        } else {
            search.style.display = "none"; // 隐藏
        }
    }
}
// 刷新
function reGet(){
    getList();
}
// 多选器
interface User {
  courseId: number
}
const selectable = (row: User) => ![1, 2].includes(row.courseId);
const multipleSelection = ref<User[]>([]);

const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val;
    console.log(val);
};
// 删除
// 单个删除
function del(index:any) {
    const id = index;
    ElMessageBox.confirm(
        `此操作将永久删除编号为 ${id} 的数据, 是否继续?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delEte(id)
                .then(() => {
                    getList();
                    ElMessage.success('删除成功!');
                })
                .catch((err) => {
                    ElMessage.error(err.msg || '删除失败');
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}
// 多个删除
const deleteClue = () => {
    let arrAy = multipleSelection.value;
    const courseIds = arrAy.map(item => item.courseId).join(',');
    console.log(courseIds);
    ElMessageBox.confirm(
        `此操作将永久删除编号为 ${courseIds} 的数据, 是否继续?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delEte(courseIds)
                .then(() => {
                    getList();
                    ElMessage.success('删除成功!');
                })
                .catch((err) => {
                    ElMessage.error(err.msg || '删除失败');
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};
// 可以用来多选的编辑
const editShow = () => {
    // 从表格当前行修改
    let arrAy = multipleSelection.value;
    let ids = arrAy[0].courseId;
    console.log(id);
    dialogVisible.value = true;
    title.value = "修改课程";
    Xiu(ids).then(res => {
        console.log(res);
        let jie = res.data;
        id.value = jie.courseId;
        ruleForm.applyTo = jie.applyTo;
        ruleForm.name = jie.name;
        ruleForm.info = jie.info;
        ruleForm.type = jie.type;
        ruleForm.price = jie.price;
    })
        .catch(err => {
            console.log(err);
        });
};

// 导出
function exportXlsx() {
    chu(pageParams).then(res => {
        console.log(res, "成功");
        // 创建一个blob对象，存储excel文件数据
        let blob = new Blob([res]);
        const link = document.createElement("a");
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob);
        link.target = "_blank";
        // 设置文件名
        let nowTime = new Date();
        link.setAttribute('download', `导出课程${nowTime.getTime()}.xlsx`);
        // 将a标签添加到页面上
        document.body.appendChild(link);
        // 触发点击事件
        link.click();
        // 移除a标签
        document.body.removeChild(link);
    })
        .catch(err => {
            console.log(err, "shibai");
        });
}


</script>

<style scoped lang="scss">
.main{
    padding: 20px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.button{
    margin-top: 20px;
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
}
.fenYe{
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
.table{
    display: block;
}
</style>